package org.wx.herostory.services.encoder;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.wx.herostory.model.User;
import org.wx.herostory.msg.GameMsgProtocol;
import org.wx.herostory.services.db.login.LoginService;
import org.wx.herostory.services.db.login.UserEntity;
import org.wx.herostory.services.util.UserManager;

/**
 * @description: 用户登录
 * @author: wangxun
 * @createDate: 2021/3/3
 * @version: 1.0
 */
@Slf4j
public class UserLoginCmdHandler implements ICmdHandler<GameMsgProtocol.UserLoginCmd> {
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserLoginCmd cmd) {
        if (null == ctx ||
                null == cmd) {
            return;
        }

        String userName = cmd.getUserName();
        String password = cmd.getPassword();

        if (null == userName ||
                null == password) {
            return;
        }

        // 获取用户实体
        LoginService.getInstance().userLogin(userName, password,(userEntity)->{
            GameMsgProtocol.UserLoginResult.Builder resultBuilder = GameMsgProtocol.UserLoginResult.newBuilder();

            if (null == userEntity) {
                resultBuilder.setUserId(-1);
                resultBuilder.setUserName("");
                resultBuilder.setHeroAvatar("");
            }  else {
                User newUser = new User();

                newUser.setUserId(userEntity.userId);

                newUser.setUserName(userEntity.userName);
                newUser.setHeroAvatar(userEntity.heroAvatar);
                newUser.setCurrHp(100);

                log.info("====当前线程={} 用户信息:{}=====",Thread.currentThread().getName(),newUser);
                UserManager.addUser(newUser);

                // 将用户 Id 保存至 Session
                ctx.channel().attr(AttributeKey.valueOf("userId")).set(newUser.getUserId());

                resultBuilder.setUserId(userEntity.userId);
                resultBuilder.setUserName(userEntity.userName);
                resultBuilder.setHeroAvatar(userEntity.heroAvatar);

            }

            GameMsgProtocol.UserLoginResult newResult = resultBuilder.build();
            ctx.writeAndFlush(newResult);
            return null;
        });


    }
}
